package handlers

import (
	"GIN-API/internal/models"
	"GIN-API/internal/service"
	"GIN-API/internal/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

type AuthHandler struct {
	userService *service.UserService
}

func NewAuthHandler(userService *service.UserService) *AuthHandler {
	return &AuthHandler{userService: userService}
}

//// ShowLoginPage 显示登录页面
//func (ah *AuthHandler) ShowLoginPage(c *gin.Context) {
//	c.HTML(http.StatusOK, "login.html", nil)
//}

// Login 用户登录
func (ah *AuthHandler) Login(c *gin.Context) {
	var loginRequest struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	// 将前端请求体里的数据绑定到 loginRequest 结构体
	if err := c.ShouldBindJSON(&loginRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
		return
	}

	// 从数据库查询用户信息
	user, err := ah.userService.GetUserByUsername(loginRequest.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
		return
	}

	//比对用户信息，主要是对前端传入的密码加密后进行比对
	if user == nil || !utils.ComparePasswords(user.Password, loginRequest.Password) {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
		return
	}

	// 生成令牌
	token, err := utils.GenerateToken(user.Username, user.Role, user.ID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
		return
	}
	// 设置令牌到响应头中
	c.Header("Authorization", "Bearer "+token)
	// 返回令牌给客户端
	c.JSON(http.StatusOK, gin.H{"token": token})
}

//// ShowRegisterPage 显示注册页面
//func (ah *AuthHandler) ShowRegisterPage(c *gin.Context) {
//	c.HTML(http.StatusOK, "register.html", nil)
//}

// Register 用户注册
func (ah *AuthHandler) Register(c *gin.Context) {
	var newUser models.User
	if err := c.ShouldBindJSON(&newUser); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
		return
	}

	hashedPassword, err := utils.HashPassword(newUser.Password)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"})
		return
	}
	newUser.Password = hashedPassword

	if err := ah.userService.CreateUser(&newUser); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册用户失败"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "用户注册成功"})
}
